<template>
  <div id="desDiv">
    <div id="headdiv">
      <span>销售退货</span>
    </div>

    <div id="sale">
      <!-- <el-button class="add-button" @click="showAddModal"
        >新增销售退货</el-button
      > -->
      <el-button
        type="primary"
        icon="el-icon-loading"
        class="audit-button"
        @click="handleAudit"
        >审核</el-button
      >

      <el-button
        class="delete-button"
        type="danger"
        icon="el-icon-delete"
        @click="handleDeleteSelected"
        >删除</el-button
      >
    </div>

    <div id="search-bar">
      <el-input
        placeholder="请输入表单中的内容进行搜索"
        prefix-icon="el-icon-search"
        v-model="searchKeyword"
        @change="fetchData"
        clearable
      ></el-input>
    </div>
    <div id="searchDate-bar">
      <!-- 日期选择器 -->
      <el-button icon="el-icon-search" circle @change="fetchData"></el-button>
      <el-date-picker
        v-model="searchDate"
        type="date"
        placeholder="选择退货日期"
        @change="fetchData"
      ></el-date-picker>
    </div>
    <!-- 表 -->
    <div id="bodydiv">
      <el-table
        border
        stripe
        :data="saleReturnData"
        style="width: 100%"
        class="centered-table"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column
          prop="return_code"
          label="销售退货单号"
          width="auto"
        ></el-table-column>
        <el-table-column
          prop="client_head"
          label="客户姓名"
          width="auto"
        ></el-table-column>
        <el-table-column
          prop="employee_name"
          label="操作人员"
          width="auto"
        ></el-table-column>

        <el-table-column
          prop="so_out_status"
          label="销售订单/出库状态"
          width="auto"
        >
          <template slot-scope="scope">
            <span
              :style="{
                color:
                  scope.row.so_out_status == 0
                    ? 'red'
                    : scope.row.so_out_status == 1
                    ? 'orange'
                    : '#2ab600',
              }"
            >
              {{
                scope.row.so_out_status == 0
                  ? "未出库"
                  : scope.row.so_out_status == 1
                  ? "待出库"
                  : "已出库"
              }}
            </span>
          </template>
        </el-table-column>

        <el-table-column prop="AuditStatus" label="审核状态" width="auto">
          <template slot-scope="scope">
            <span
              :style="{
                color: scope.row.auditStatus == true ? '#2ab600' : 'red',
              }"
            >
              {{ scope.row.auditStatus == true ? "已审核" : "未审核" }}
            </span>
          </template>
        </el-table-column>

        <el-table-column prop="return_date" label="退货日期" width="auto">
          <template slot-scope="scope">
            <span>{{ formatDate(scope.row.return_date) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250">
          <template slot-scope="scope">
            <el-button
              size="mini"
              :type="
                scope.row.return_status == 1 || scope.row.return_status == 2
                  ? 'danger'
                  : 'primary'
              "
              :icon="scope.row.return_status == 0 ? 'el-icon-back' : ''"
              :disabled="
                scope.row.return_status == 1 || scope.row.return_status == 2
              "
              @click="handleReturn(scope.row)"
            >
              {{
                scope.row.return_status == 0
                  ? "退货"
                  : scope.row.return_status == 1
                  ? "待退货审核"
                  : "已退货"
              }}
            </el-button>

            <el-button
              size="mini"
              type="primary"
              icon="el-icon-view"
              @click="handleSee(scope.row)"
              >退货详情</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 下划线分隔 -->
    <el-divider></el-divider>
    <!-- 尾部 -->
    <div id="taildiv">
      <!-- 分页 -->
      <el-pagination
        class="pagination"
        @size-change="change"
        @current-change="Ymchange"
        :current-page="currentPage"
        :page-sizes="[10, 15, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="rows"
      >
      </el-pagination>
    </div>
    <!-- 模态框查询销售订单 -->
    <!-- <el-dialog
      title="选择退货订单"
      :visible.sync="dialogVisible"
      width="60%"
      :before-close="handleClose"
    >
      <el-divider></el-divider> -->
    <!-- 搜索框 -->
    <!-- <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            placeholder="请输入货品编号/名称"
            v-model="searchKeyword2"
            class="input-with-select"
            prefix-icon="el-icon-search"
            @change="fetchDataSaleOrder"
          >
          </el-input>
        </el-col>
      </el-row> -->

    <!-- <el-table
        ref="tableName"
        :data="saleOrderData"
        border
        stripe
        class="centered-table"
        @selection-change="handleSelectionChange2"
      >
        <el-table-column type="selection" width="55"></el-table-column>

        <el-table-column
          prop="so_code"
          label="销售订单编号"
          width="auto"
        ></el-table-column>
        <el-table-column
          prop="client_head"
          label="客户编码"
          width="auto"
        ></el-table-column>
        <el-table-column prop="so_types" label="产品种类" width="auto">
          <template slot-scope="scope"> {{ scope.row.so_types }} 种 </template>
        </el-table-column>
        <el-table-column
          prop="so_toNum"
          label="总销售数量"
          width="auto"
        ></el-table-column>

        <el-table-column prop="so_status" label="订单状态" width="auto">
          <template slot-scope="scope">
            <span
              :style="{
                color:
                  scope.row.so_status == 0
                    ? 'red'
                    : scope.row.so_status == 1
                    ? 'orange'
                    : '#2ab600',
              }"
            >
              {{
                scope.row.so_status == 0
                  ? "未出库"
                  : scope.row.so_status == 1
                  ? "待出库"
                  : "已出库"
              }}
            </span>
          </template>
        </el-table-column>

        <el-table-column
          prop="employee_name"
          label="操作人员"
        ></el-table-column>
        <el-table-column label="销售日期">
          <template slot-scope="scope">
            <span>{{ formatDate(scope.row.so_sales_date) }}</span>
          </template>
        </el-table-column>
      </el-table>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAddGoods">确定</el-button>
      </span>
    </el-dialog> -->

    <!-- 退货详情模态框 -->
    <el-dialog title="" :visible.sync="IsDetails" width="50%">
      <h3>销售订单退货详情</h3>
      <el-form label-width="80px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="退货单号">
              <el-input
                v-model="ReturnDetails.return_code"
                style="width: 200px"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="销售单号">
              <el-input
                v-model="ReturnDetails.so_code"
                style="width: 200px"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="退货日期">
              <el-date-picker
                style="width: 200px"
                v-model="ReturnDetails.return_date"
                type="date"
                format="yyyy-MM-dd"
                placeholder="请选择日期"
                disabled
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户名称">
              <el-input
                v-model="ReturnDetails.client_head"
                style="width: 200px"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系方式">
              <el-input
                v-model="ReturnDetails.client_phone"
                placeholder="请输入"
                style="width: 200px"
                disabled
              />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="审核人">
              <el-input
                v-model="ReturnDetails.auditor"
                style="width: 200px"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="审核时间">
              <el-input
                v-model="ReturnDetails.auditTime"
                style="width: 200px"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="审核状态">
              <el-input v-model="displayText" style="width: 200px" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="操作人员">
              <el-input
                v-model="ReturnDetails.employee_name"
                style="width: 200px"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="退货原因">
              <el-input
                v-model="ReturnDetails.returmReason"
                placeholder="请输入"
                type="textarea"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <h3>退货产品明细</h3>

      <div style="overflow-x: auto">
        <el-table
          :data="saleReturnDataC"
          border
          stripe
          style="width: 100%"
          class="dataTable"
        >
          <el-table-column
            prop="return_C_Id"
            type="index"
            label="序号"
          ></el-table-column>
          <el-table-column
            prop="orders_product_name"
            label="产品名称"
            width="auto"
          ></el-table-column>

          <el-table-column prop="orders_unit" label="单位" width="auto">
          </el-table-column>

          <el-table-column
            prop="return_quantity"
            label="销售数量"
            width="auto"
          ></el-table-column>

          <el-table-column
            prop="w_Name"
            label="退货入库仓库"
            width="auto"
          ></el-table-column>

          <el-table-column
            prop="return_quantity"
            label="退货数量"
            width="auto"
          ></el-table-column>

          <el-table-column
            prop="return_remark"
            label="备注"
            width="auto"
          ></el-table-column>
        </el-table>
        <div class="pagination-wrapper">
          <el-pagination
            @size-change="changeModel"
            @current-change="YmchangeModel"
            :current-page="currentPage2"
            :page-sizes="[6, 10, 20, 50]"
            :page-size="pageSize2"
            layout="total, sizes, prev, pager, next, jumper"
            :total="modelfroms"
          ></el-pagination>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import moment from "moment";
import $http from "@/routers/base";

export default {
  data() {
    return {
      dialogVisible: false,
      IsDetails: false, //退货详情模态框
      Ycchange: false,
      currentPage: 1, //当前页
      pageSize: 10, //每页显示数
      rows: 0, //总行数
      searchKeyword: "", //搜索框
      searchDate: "", //日期框
      searchKeyword2: "", //模态框搜索框
      dateString: "",
      saleReturnData: [], // 销售退货数据
      where: "",
      selectedRows: [], // 存储当前选中的行
      selectedRows2: [],
      saleOrderData: [], //销售订单数据

      currentPage2: 1, //当前页
      pageSize2: 3, //每页显示数
      modelfroms: 0,
      saleReturnDataC: [], //销售退货从表

      saleOutData: [], //销售出库数据
      ReturnDetails: {
        return_code: "",
        so_code: "",
        return_date: "",
        client_head: "",
        client_phone: "",
        auditor: "",
        auditTime: "",
        auditStatus: "",
        employee_name: "",
        returmReason: "",
      },
      selectedModelId: 0,
      sal_sales_ReturnReturn_Id: "",
    };
  },
  methods: {
    //日期转型
    formatDate(dateString) {
      if (!dateString) {
        return "";
      }
      const date = new Date(dateString);
      if (isNaN(date.getTime())) {
        return "";
      }
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, "0");
      const day = date.getDate().toString().padStart(2, "0");
      return `${year}-${month}-${day}`;
    },
    //选中行
    handleSelectionChange(selection) {
      this.selectedRows = selection; // 更新选中的行
    },
    handleSelectionChange2(selection) {
      this.selectedRows2 = selection; // 更新选中的行
    },
    //查询销售退货数据
    fetchData() {
      this.dateString = moment(this.searchDate).format("YYYY-MM-DD");
      this.where = "1=1";

      if (this.searchDate) {
        this.where += `and (CAST(return_date AS DATE) ='${this.dateString}')`;
      }
      if (this.searchKeyword) {
        this.where += `and (client_head like '%${this.searchKeyword}%' or employee_name like '%${this.searchKeyword}%' or Return_code like '%${this.searchKeyword}%')`;
      }

      $http
        .get("SalesReturn/getFenYe", {
          params: {
            currentPage: this.currentPage,
            pageSize: this.pageSize,
            where: this.where,
          },
        })
        .then((res) => {
          this.saleReturnData = res.saleReturnData;
          this.rows = res.rows;
          console.log("sadkanuab" + this.rows);
        })
        .catch((error) => {
          console.error("Error fetching client data: ", error);
        });
    },
    change: function (size) {
      this.pageSize = size;
      this.currentPage = 1;
      this.fetchData();
    },
    Ymchange: function (page) {
      this.currentPage = page;
      this.fetchData();
    },

    //修改分页
    fetchUpaheModeFrom() {
      this.where = "sal_sales_ReturnReturn_Id=" + this.selectedModelId;
      // 向后端请求数据，并更新客户数据和总条数
      $http
        .get("SalesReturn/getFenYeC", {
          params: {
            currentPage: this.currentPage2,
            pageSize: this.pageSize2,
            where: this.where,
          },
        })
        .then((res) => {
          this.saleReturnDataC = res.saleReturnDataC;
          this.modelfroms = res.rows;
          console.log("数量" + this.modelfroms);
        })
        .catch((error) => {
          console.error("Error fetching client data: ", error);
        });
    },
    changeModel: function (size) {
      this.pageSize2 = size;
      this.currentPage2 = 1;
      this.fetchUpaheModeFrom();
    },
    YmchangeModel: function (page) {
      this.currentPage2 = page;
      this.fetchUpaheModeFrom(); // 重新获取数据
    },

    //查询模态框销售订单数据
    fetchDataSaleOrder() {
      this.where = "1=1 ";
      if (this.searchKeyword2) {
        this.where += `and (client_head like '%${this.searchKeyword2}%' or employee_name like '%${this.searchKeyword2}%')`;
      }
      $http
        .get("SalesOrder/getFenYe", {
          params: {
            currentPage: this.currentPage,
            pageSize: this.pageSize,
            where: this.where,
          },
        })
        .then((res) => {
          this.saleOrderData = res.saleOrderData;
          this.rows = res.rows;
        })
        .catch((error) => {
          console.error("Error fetching client data: ", error);
        });
    },
    //查询模态框销售出库数据
    async fetchSaleOut() {
      this.where = "1=1";
      $http
        .get("SalesOut/getFenYe", {
          params: {
            currentPage: this.currentPage,
            pageSize: this.pageSize,
            where: this.where,
          },
        })
        .then((res) => {
          this.saleOutData = res.saleOutData;
          this.rows = res.rows;
        })
        .catch((error) => {
          console.error("Error fetching client data: ", error);
        });
    },
    //删除
    handleDeleteSelected() {
      if (this.selectedRows.length === 0) {
        this.$message.warning("请至少选择一个进行删除");
        return;
      }
      this.$confirm("此操作将删除选中的销售出库订单, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.selectedRows.forEach((row) => {
            this.deleteSaleReturn(row.return_Id);
          });
          this.fetchData();
          this.selectedRows = [];
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //删除主方法
    deleteSaleReturn(return_Id) {
      $http
        .delete(`SalesReturn/Delete/${return_Id}`)
        .then((response) => {
          this.$message({
            message: response,
            type: "success",
          });
          this.fetchData();
        })
        .catch((error) => {
          this.$message.error("删除失败，请稍后再试");
          console.error("Delete error:", error);
        });
    },
    handleClose(done) {
      done();
    },
    // //添加模态框确定
    // confirmAddGoods() {
    //   const selectedRows2 = this.$refs.tableName.selection; // 获取所有选中的行数据
    //   // 检查是否至少选择了一行
    //   if (selectedRows2.length > 0) {
    //     // 遍历选中的每一行数据
    //     selectedRows2.forEach((row) => {
    //       const postData = {
    //         return_code: row.so_code,
    //         client_head: row.client_head,
    //         return_Num: 0,
    //         w_Name: "暂无",
    //         employee_name: "暂无",
    //         return_status: "0",
    //         return_date: this.formatDate(new Date()), // 退货日期，这里使用当前日期
    //       };
    //       //发送每一行数据到服务器进行添加;
    //       $http
    //         .post("SalesReturn/AddReturn", postData)
    //         .then((res) => {
    //           if (res) {
    //             //this.$message({
    //             // message: "添加成功！",
    //             // type: "success",
    //             //});
    //             this.fetchData();
    //             this.dialogVisible = false;
    //           } else {
    //             this.$message({
    //               message: "添加失败！",
    //               type: "error",
    //             });
    //           }
    //         })
    //         .catch((error) => {
    //           console.error("添加失败:", error);
    //           this.$message.error("添加失败，请稍后重试！");
    //         });
    //     });
    //   } else {
    //     this.$message.warning("请至少选择一行数据！");
    //   }
    // },
    //退货详情
    handleSee(row) {
      this.IsDetails = true;
      this.selectedModelId = row.return_Id;
      this.sal_sales_ReturnReturn_Id = this.selectedModelId;
      this.fetchData();
      this.fetchUpaheModeFrom();
      this.$set(this.ReturnDetails, "return_code", row.return_code);
      this.$set(this.ReturnDetails, "so_code", row.so_code);
      this.$set(this.ReturnDetails, "return_date", row.return_date);
      this.$set(this.ReturnDetails, "client_head", row.client_head);
      this.$set(this.ReturnDetails, "client_phone", row.client_phone);
      this.$set(this.ReturnDetails, "auditor", row.auditor);
      this.$set(this.ReturnDetails, "auditTime", row.auditTime);
      this.$set(this.ReturnDetails, "auditStatus", row.auditStatus);
      this.$set(this.ReturnDetails, "employee_name", row.employee_name);
      this.$set(this.ReturnDetails, "returmReason", row.returmReason);
    },
    //销售退货审核
    handleAudit() {
      if (this.selectedRows.length === 0) {
        this.$message.warning("请至少选择一个销售订单进行审核");
        return;
      }
      const auditedRows = this.selectedRows.filter(
        (row) => row.return_status == "2"
      );
      if (auditedRows.length > 0) {
        this.$message.warning(
          "选中的销售退货中已有订单已经退货成功，不能再次退货"
        );
        return;
      }

      this.$confirm("此操作将审核选中的销售订单, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.selectedRows.forEach((row) => {
            this.auditSaleOrder(row.return_Id);
          });
          this.selectedRows = [];
          this.fetchData();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消审核",
          });
        });
    },
    //审核方法
    auditSaleOrder(return_Id) {
      $http
        .post(`SalesReturn/AuditSalesReturn/${return_Id}`)
        .then((response) => {
          this.$message({
            message: response,
            type: "success",
          });
          this.fetchData();
        })
        .catch((error) => {
          this.$message.error("审核失败，请稍后再试");
          console.error("Audit error:", error);
        });
    },
  },
  computed: {
    displayText() {
      return this.ReturnDetails.auditStatus ? "已审核" : "未审核";
    },
  },
  mounted() {
    this.fetchData();
    this.fetchDataSaleOrder();
    this.fetchSaleOut();
    this.fetchUpaheModeFrom();
  },
};
</script>
<style scoped src="../CSS/SaleOrder.css"></style>
<style scoped></style>
